﻿///***************************************************************
/// 시  스  템 : Updms.Com
/// 단위시스템 : COM
/// 계      층 : Presentation Layer
/// 프로그램명 : Com1013m
/// 파  일  명 : Com1013m.aspx.cs
/// 설      명 : 사용자관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-28 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Com.Exe;


namespace Updms.Com
{
	public partial class Com1013m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Com1013m";
		public static readonly string gs_path_info = "/updms/Com/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Com com = new CommCode.Com(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	// 아이디
		protected string kw2 = "";	// 이름
		protected string kw3 = "";	// 권한
		protected string kw4 = "";	// 사용자구분

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SetCheckUserId("CLEAR");
				SelectProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetUserDiv();
			SetUserLevel();
			SetLanguageSet();
			SetStartPage("");
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			ddl_start_page.Attributes.Add("onChange", "chkDisableOption(this)");
			
			//onKeyPress이벤트 (엔터검색)
			txt_search_user_id.Attributes.Add("onkeypress", "enterSearch(event)");
			txt_search_nm.Attributes.Add("onkeypress", "enterSearch(event)");
			txt_user_id.Attributes.Add("onkeypress", "enterCheckUserId(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = txt_search_user_id.Text.Trim();
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						txt_search_user_id.Text = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_nm.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_nm.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = ddl_search_user_level.SelectedValue;
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						ddl_search_user_level.SelectedValue = kw3;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						kw4 = ddl_search_user_div.SelectedValue;
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						ddl_search_user_div.SelectedValue = kw4;
					}
					break;
				case "SEARCH":
					kw1 = txt_search_user_id.Text.Trim();
					kw2 = txt_search_nm.Text.Trim();
					kw3 = ddl_search_user_level.SelectedValue;
					kw4 = ddl_search_user_div.SelectedValue;
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw3 = ConversionUtil.CompareReplace(ddl_search_user_level.SelectedItem.Text, DDL_SELECT, "-");
			string ls_kw4 = ConversionUtil.CompareReplace(ddl_search_user_div.SelectedItem.Text, DDL_SELECT, "-");

			lbl_search_keyword.Text = kw1 + " / " + kw2 + " / " + ls_kw3 + " / " + ls_kw4;
		}

		#endregion

		#region 마스터 Method (SetUserLevel, SetLanguageSet)

		//권한
		private void SetUserLevel()
		{
			ddl_search_user_level.Items.Insert(0, new ListItem(DDL_SELECT, ""));
			ddl_user_level.Items.Insert(0, new ListItem(DDL_SELECT, ""));

			for (int i = 1; i <= 9; i++)
			{
				string ls_i = i.ToString();
				ddl_search_user_level.Items.Insert(i, new ListItem(ls_i, ls_i));
				ddl_user_level.Items.Insert(i, new ListItem(ls_i, ls_i));
			}
		}
		
		//언어
		private void SetLanguageSet()
		{
			com.SetLanguageSet(ddl_language_set, LANG_SET);
		}

		#endregion

		#region 디테일 Method (SetUserDiv, SetStartPage, SetChangeUserId)

		//유저구분
		private void SetUserDiv()
		{
			com.SetUserDiv(ddl_search_user_div);
			com.SetUserDiv(ddl_user_div);

			ddl_search_user_div.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		// 선택된 권한이 접근가능한 프로그램만 가져온다
		private void SetStartPage(string ls_access_level)
		{
			if (String.IsNullOrEmpty(ls_access_level))
			{
				ddl_start_page.Items.Clear();
				ddl_start_page.Items.Insert(0, new ListItem(GetXmlMsg("STR_001"), "-"));	//접근권한을 먼저 선택하세요
			}
			else
			{
				DataSet lo_ds = new DataSet();
				DataPack lo_dp = new DataPack();
				Com1011m_NT _Com1011m_NT = new Com1011m_NT();

				lo_dp.AddProperty("ls_access_level", typeof(string), ls_access_level);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Com1011m_NT.GetStartPage(lo_dp));

				ddl_start_page.Items.Clear();
				ddl_start_page.DataSource = lo_ds;
				ddl_start_page.DataMember = "UPDMS_COM_PGM";
				ddl_start_page.DataTextField = "Text";
				ddl_start_page.DataValueField = "Value";
				ddl_start_page.DataBind();
			}
		}

		//권한변경시
		protected void ddl_user_level_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetStartPage(ddl_user_level.SelectedValue);
		}

		//SetChangeUserId
		public String SetChangeUserId()
		{
			return txt_user_id.Text.Trim();
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_user_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_user_level", typeof(string), kw3);
			lo_dp.AddProperty("ls_user_div", typeof(string), kw4);

			using (Com1013m_NT _Com1013m_NT = new Com1013m_NT())
			{
				li_row_count = _Com1013m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Com1013m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&page=");

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Com1013m_RT _Com1013m_RT = new Com1013m_RT())
			{
				int li_return = _Com1013m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Com1013m_RT _Com1013m_RT = new Com1013m_RT())
			{
				int li_return = _Com1013m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Com1013m_RT _Com1013m_RT = new Com1013m_RT())
			{
				int li_return = _Com1013m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue, SetCheckUserId

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			string ls_pw = "";
			
			lo_dp.AddProperty("User_Id", typeof(string), 		txt_user_id.Text);
			lo_dp.AddProperty("Nm", typeof(string), 			ConversionUtil.DefaultValue(txt_nm.Text));
			lo_dp.AddProperty("Email", typeof(string), 			ConversionUtil.DefaultValue(txt_email.Text));
			lo_dp.AddProperty("User_Level", typeof(string), 	ddl_user_level.SelectedValue);
			lo_dp.AddProperty("User_Div", typeof(string), 		ddl_user_div.SelectedValue);
			lo_dp.AddProperty("Start_Page", typeof(string), 	ddl_start_page.SelectedValue);
			lo_dp.AddProperty("Language_Set", typeof(string), 	ddl_language_set.SelectedValue);
			lo_dp.AddProperty("Use_Yn", typeof(string), 		rbl_use_yn.SelectedValue);
			lo_dp.AddProperty("Remark", typeof(string), 		ConversionUtil.DefaultValue(txt_remark.Text));
			lo_dp.AddProperty("Create_User", typeof(string), 	USER_ID);
			lo_dp.AddProperty("Create_Dt", typeof(string), 		"");
			lo_dp.AddProperty("Update_User", typeof(string), 	USER_ID);
			lo_dp.AddProperty("Update_Dt", typeof(string), 		"");

			if (String.IsNullOrEmpty(txt_pw.Text))
			{
				ls_pw = lbl_pw.Text;
			}
			else
			{
				ls_pw = FormsAuthentication.HashPasswordForStoringInConfigFile(txt_pw.Text, "SHA1");
			}

			lo_dp.AddProperty("Pw", typeof(string), ls_pw);

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			h_no.Value	= "";
			txt_user_id.Text = "";
			lbl_pw.Text = "";
			txt_nm.Text = "";
			txt_email.Text = "";
			ddl_user_level.SelectedIndex = 0;
			SetStartPage("");	//빈값으로 바인딩
			ddl_user_div.SelectedIndex = 0;
			ddl_language_set.SelectedIndex = 0;
			rbl_use_yn.SelectedIndex = 0;
			txt_remark.Text = "";

			SetCheckUserId("CLEAR");
		}

		//모드별 아이디 중복체크 설정
		private void SetCheckUserId(string div)
		{
			//초기화
			h_check_user_id.Value = "";
			txt_user_id.Enabled = true;
			txt_pw.Enabled = true;
			lbtn_user_id_check.Visible = true;
			ibtn_change_pw.Visible = false;
			switch(div)
			{
				case "MODIFY":	//목록 클릭
					h_check_user_id.Value = "Y";
					txt_user_id.Enabled = false;
					txt_pw.Enabled = false;
					lbtn_user_id_check.Visible = false;
					ibtn_change_pw.Visible = true;
					break;
				case "CLEAR":	//초기화
					h_check_user_id.Value = "";
					txt_user_id.Enabled = true;
					break;
				case "CHECK_OK":	//중복체크 클릭(중복아이디 없으면)
					h_check_user_id.Value = "Y";
					txt_user_id.Enabled = false;					
					break;
			}
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//사용여부
				e.Row.Cells[12].Attributes.Add("class", (e.Row.Cells[12].Text == "Y") ? "color_darkred" : "color_gray");
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();//0.체크박스
			h_no.Value						= row.Cells[1].Text.ToString();								//1.번호
			txt_user_id.Text				= lbtn_rc.Text;												//2.User_Id (template)
			lbl_pw.Text						= gv.DataKeys[row.RowIndex].Values["Pw"].ToString();		//3.Pw
			txt_nm.Text						= row.Cells[4].Text.Trim();									//4.Nm
			txt_email.Text					= row.Cells[5].Text.Trim();									//5.Email
			ddl_user_level.SelectedValue	= row.Cells[6].Text.Trim();									//6.User_Level
			ddl_user_div.SelectedValue		= gv.DataKeys[row.RowIndex].Values["User_Div"].ToString();	//7.User_Div
			
			//시작페이지 바인딩
			SetStartPage(ddl_user_level.SelectedValue);
																										//8.User_Div_Nm
			//DB에 등록된 사용자의 시작페이지가 ddl_start_page에 없는경우 '개인정보수정'페이지로 바인딩
			ddl_start_page.SelectedValue 
				= WebControlUtil.CheckDdlValue(ddl_start_page, gv.DataKeys[row.RowIndex].Values["Start_Page"].ToString(), "Com1015m");//10.Start_Page
																										//9.Pgm_Nm
			ddl_language_set.SelectedValue	= row.Cells[11].Text.Trim();								//11.Language_Set
			rbl_use_yn.SelectedValue		= row.Cells[12].Text.Trim();								//12.Use_Yn
			txt_remark.Text					= row.Cells[13].Text.Trim();								//13.Remark

			SetCheckUserId("MODIFY");
		}		

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_COM_USER_MGT", "User_Id", txt_user_id.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");
				LinkButton lbtn_rc = (LinkButton)row.FindControl("lbtn_rc");

				if (cb.Checked)
				{
					string ls_user_id = lbtn_rc.Text.Trim();
					sb.Append("<UPDMS_COM_USER_MGT>");
					sb.Append("<User_Id>" + ls_user_id + "</User_Id>");
					sb.Append("</UPDMS_COM_USER_MGT>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_user_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_user_level", typeof(string), kw3);
			lo_dp.AddProperty("ls_user_div", typeof(string), kw4);

			using (Com1013m_NT _Com1013m_NT = new Com1013m_NT())
			{
				li_row_count = _Com1013m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				lo_ds.Merge(_Com1013m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//아이디 중복체크
		protected void lbtn_user_id_check_Click(object sender, EventArgs e)
		{
			string ls_user_id = txt_user_id.Text.Trim();
			bool lb_rslt = false;

			using (Com1013m_NT _Com1013m_NT = new Com1013m_NT())
			{
				lb_rslt = _Com1013m_NT.CheckExistUserId(ls_user_id);
			}

			if (lb_rslt)
			{
				SetCheckUserId("CLEAR");
				CallMsgBoxInAjax("MSG_ERR_194");//이미 등록된 아이디입니다
			}
			else
			{
				SetCheckUserId("CHECK_OK");
				CallMsgBoxInAjax("MSG_INF_023");//등록가능한 아이디입니다
			}
		}

		#endregion

	}
}
